/*
 * @Author: gggg 1263457581@qq.com
 * @Date: 2025-06-06 15:52:26
 * @LastEditors: gggg 1263457581@qq.com
 * @LastEditTime: 2025-06-06 15:53:35
 * @FilePath: /algorithm-and-data-struct/pool/Semaphore.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#ifndef _SEMAPHORE_H
#define _SEMAPHORE_H
#include <mutex>
#include <condition_variable>
using namespace std;

class Semaphore
{
public:
    Semaphore(long count = 0) : count(count) {}
    //V操作，唤醒
    void signal()
    {
        unique_lock<mutex> unique(mt);
        ++count;
        if (count <= 0)
        cond.notify_one();
    }
    //P操作，阻塞
    void wait()
    {
        unique_lock<mutex> unique(mt);
        --count;
        if (count < 0)
        cond.wait(unique);
    }

private:
    mutex mt;
    condition_variable cond;
    long count;
};
#endif